package com.lingyu.jsjx.controller;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.lingyu.jsjx.domain.AwardRecord;
import com.lingyu.jsjx.service.IAwardRecordService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 我的成就
 *
 * @author ruoyi
 * @date 2025-08-08
 */
@RestController
@RequestMapping("/awardRecord")
public class AwardRecordController extends BaseController {
    @Autowired
    private IAwardRecordService awardRecordService;

    /**
     * 查询我的成就列表
     */
    @RequiresPermissions("jsjx:awardRecord:list")
    @GetMapping("/list")
    public TableDataInfo list(AwardRecord awardRecord) {
        startPage();
        List<AwardRecord> list = awardRecordService.selectAwardRecordList(awardRecord);
        return getDataTable(list);
    }

    /**
     * 导出我的成就列表
     */
    @RequiresPermissions("jsjx:awardRecord:export")
    @Log(title = "我的成就", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AwardRecord awardRecord) {
        List<AwardRecord> list = awardRecordService.selectAwardRecordList(awardRecord);
        ExcelUtil<AwardRecord> util = new ExcelUtil<AwardRecord>(AwardRecord.class);
        util.exportExcel(response, list, "我的成就数据");
    }

    /**
     * 获取我的成就详细信息
     */
    @RequiresPermissions("jsjx:awardRecord:query")
    @GetMapping(value = "/{awardId}")
    public AjaxResult getInfo(@PathVariable("awardId") Long awardId) {
        return success(awardRecordService.selectAwardRecordByAwardId(awardId));
    }

    /**
     * 新增我的成就
     */
    @RequiresPermissions("jsjx:awardRecord:add")
    @Log(title = "我的成就", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AwardRecord awardRecord) {
        return toAjax(awardRecordService.insertAwardRecord(awardRecord));
    }

    /**
     * 修改我的成就
     */
    @RequiresPermissions("jsjx:awardRecord:edit")
    @Log(title = "我的成就", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AwardRecord awardRecord) {
        return toAjax(awardRecordService.updateAwardRecord(awardRecord));
    }

    /**
     * 删除我的成就
     */
    @RequiresPermissions("jsjx:awardRecord:remove")
    @Log(title = "我的成就", businessType = BusinessType.DELETE)
    @DeleteMapping("/{awardIds}")
    public AjaxResult remove(@PathVariable Long[] awardIds) {
        return toAjax(awardRecordService.deleteAwardRecordByAwardIds(awardIds));
    }

    /**
     * 教学成就
     *
     * @return
     */
    @GetMapping(value = "/queryAwardLevelCount")
    public AjaxResult queryAwardLevelCount() {
        List<Map<String, Object>> list = awardRecordService.selectAwardLevelCount();
        Optional<Integer> minYear = list.stream()
                .map(map -> map.get("year"))
                .filter(Objects::nonNull)
                .map(year -> {
                    if (year instanceof Integer) {
                        return (Integer) year;
                    } else if (year instanceof String) {
                        try {
                            return Integer.parseInt((String) year);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .min(Integer::compareTo);
        Optional<Integer> maxYear = list.stream()
                .map(map -> map.get("year"))
                .filter(Objects::nonNull)
                .map(year -> {
                    if (year instanceof Integer) {
                        return (Integer) year;
                    } else if (year instanceof String) {
                        try {
                            return Integer.parseInt((String) year);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .max(Integer::compareTo);
        List<Integer> yearList = new ArrayList<>();
        List<Long> countryList = new ArrayList<>();
        List<Long> provinceList = new ArrayList<>();
        List<Long> cityList = new ArrayList<>();
        List<Long> schoolList = new ArrayList<>();
        if(minYear.isPresent() && maxYear.isPresent()) {
            for (Integer i = minYear.get(); i <= maxYear.get(); i++) {
                final Integer year = i;
                yearList.add(i);
                Long result1 = list.stream()
                        .filter(map -> Objects.equals(map.get("year"), year) && // 使用 year 替代 i
                                Objects.equals(map.get("award_level_id"), 179L))
                        .findFirst()
                        .map(map -> (Long) map.get("count"))
                        .orElse(0L);
                Long result2 = list.stream()
                        .filter(map -> Objects.equals(map.get("year"), year) && // 使用 year 替代 i
                                Objects.equals(map.get("award_level_id"), 180L))
                        .findFirst()
                        .map(map -> (Long) map.get("count"))
                        .orElse(0L);
                Long result3 = list.stream()
                        .filter(map -> Objects.equals(map.get("year"), year) && // 使用 year 替代 i
                                Objects.equals(map.get("award_level_id"), 181L))
                        .findFirst()
                        .map(map -> (Long) map.get("count"))
                        .orElse(0L);
                Long result4 = list.stream()
                        .filter(map -> Objects.equals(map.get("year"), year) && // 使用 year 替代 i
                                Objects.equals(map.get("award_level_id"), 182L))
                        .findFirst()
                        .map(map -> (Long) map.get("count"))
                        .orElse(0L);
                countryList.add(result1);
                provinceList.add(result2);
                cityList.add(result3);
                schoolList.add(result4);
            }
        }
        JSONObject resultMap = new JSONObject();
        resultMap.put("yearList", yearList);
        resultMap.put("countryList", countryList);
        resultMap.put("provinceList", provinceList);
        resultMap.put("cityList", cityList);
        resultMap.put("schoolList", schoolList);

        return success(resultMap);
    }

    @GetMapping(value = "/queryCountGroupByUserId")
    public AjaxResult queryCountGroupByUserId() {
        return success(awardRecordService.selectCountGroupByUserId());
    }
}
